package com.deve.pig.api;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import my.utils.Constants;
import my.utils.JacksonUtil;
import my.utils.LocationUtil;
import my.utils.MerchantDistanceComparator;
import my.utils.Pagination;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.deve.pig.controller.BaseController;
import com.deve.pig.model.Category;
import com.deve.pig.model.CategoryExample;
import com.deve.pig.model.Merchant;
import com.deve.pig.model.MerchantBranchStore;
import com.deve.pig.model.MerchantBranchStoreExample;
import com.deve.pig.model.MerchantExample;
import com.deve.pig.model.MerchantImages;
import com.deve.pig.model.MerchantImagesExample;
import com.deve.pig.service.category.ICategoryService;
import com.deve.pig.service.merchant.IMerchantBranchStoreService;
import com.deve.pig.service.merchant.IMerchantGoodsService;
import com.deve.pig.service.merchant.IMerchantImagesService;
import com.deve.pig.service.merchant.IMerchantService;


@Controller
@RequestMapping("/api/merchant")
@Scope(BeanDefinition.SCOPE_PROTOTYPE)
public class ApiMerchantController extends BaseController{
	private static final Log log = LogFactory.getLog(ApiMerchantController.class);
	@Resource
	private IMerchantService merchantService;
	@Resource
	private IMerchantBranchStoreService merchantBranchStoreService;
	@Resource
	private IMerchantGoodsService merchantGoodsService;
	@Resource
	private IMerchantImagesService merchantImagesService;
	@Resource
	private ICategoryService categoryService;
	
	
	
	@ExceptionHandler({Exception.class})
	@ResponseBody
	public String handlerException(Exception e){
		log.error("----------->>>handleException Error",e);
		jsonMap.clear();
		jsonMap.put("status", Constants.Base.FAIL);
		jsonMap.put("msg", "System Failed:" + e.getMessage());
		String resp = JacksonUtil.toJson(jsonMap);
		log.info("--------->>>resp is " + resp);
		return resp;
	}
	
	
	@RequestMapping("/queryMerchantList")
	@ResponseBody
	public Map<String, Object> queryMerchantList(
							 Boolean isDiscount, //是否优惠商家
							 Integer orderTypee, //排序类型 1：时间排序  2：距离排序
							 Integer distanceType, //距离 1：1千米 2 ：3千米  3： 5千米
							 Integer categoryId,  //分类
			 				 Float userLo,//用户app经度
			 				 Float userLa, //用户app纬度
							 Integer currentPage,
							 Integer pageSize,
							 Model model,HttpServletRequest request,HttpServletResponse response){
		jsonMap.clear();
		Map<String, Object> params = super.getRequestParameters(request);
		if (currentPage==null || currentPage<=0) currentPage = Pagination.CURRENTPAGE;
		if (pageSize==null||pageSize <= 0) pageSize = 5;
		if (isDiscount==null) isDiscount = true;
		if (distanceType==null) distanceType = 2;
		if (orderTypee==null) orderTypee = 2;
		if (categoryId==null) categoryId = 0;
		//无法定位用户时....
		if (userLo==null) userLo = 0f;
		if (userLa==null) userLa = 0f;
		
		
		MerchantExample merchantExample = new MerchantExample();
        MerchantExample.Criteria criteria = merchantExample.createCriteria();
        criteria.andIsPublishEqualTo((byte)1); //发布了的商品
        if(isDiscount){
        	criteria.andIsDiscountEqualTo((byte)1);
        }
        if(categoryId>0){
    		criteria.andCategoryIdEqualTo(categoryId);
    	}
        List<Merchant> listMerchant =  merchantService.findByCriteria(merchantExample);
        //距离 
        //计算经纬度
        System.out.println(listMerchant.size());
        filterByDistanceType(distanceType,userLo,userLa,listMerchant);
        System.out.println(listMerchant.size());
        
        //----------排序---------
        //时间排序
        if(orderTypee == 1){
        	Collections.sort(listMerchant,new Comparator<Merchant>(){
				@Override
				public int compare(Merchant o1, Merchant o2) {
					return o1.getPublishTime().compareTo(o2.getPublishTime());
				}
        	});
        }else if(orderTypee == 2){
        	//距离排序
        	Collections.sort(listMerchant, new MerchantDistanceComparator());
        }
        //分页
        Pagination page = computPagination(currentPage,pageSize,listMerchant);
        List<Merchant> items =  (List<Merchant>) page.getItems();
		
		jsonMap.put("status", Constants.Base.SUCCESS);
		jsonMap.put("msg", "成功");
		jsonMap.put("datas", items);
		jsonMap.put("currentPage", page.getCurrentPage());
		jsonMap.put("pageSize",page.getPageSize());
		jsonMap.put("totalCount", page.getTotalCount());
		return jsonMap;
		
	}
	
	
	
	@RequestMapping("/queryMerchantDetailById")
	@ResponseBody
	public Map<String, Object> queryMerchantDetailById(int id,Integer currentPage,Integer pageSize){
		jsonMap.clear();
		Merchant mer = merchantService.findById(id);
		//商家图片库
		MerchantImagesExample merchantImagesExample = new MerchantImagesExample();
		MerchantImagesExample.Criteria criteriaImages =  merchantImagesExample.createCriteria();
		criteriaImages.andMerchantIdEqualTo(id);
		List<MerchantImages> listMerImages = merchantImagesService.findByCriteria(merchantImagesExample);
		
		//商家分店
		MerchantBranchStoreExample criteriaExample = new MerchantBranchStoreExample();
		MerchantBranchStoreExample.Criteria criteria =  criteriaExample.createCriteria();
		criteria.andMerchantIdEqualTo(id);
		List<MerchantBranchStore> listMerStore = merchantBranchStoreService.findByCriteria(criteriaExample);
		
		//商家优惠商品
		if (currentPage==null || currentPage<=0) currentPage = Pagination.CURRENTPAGE;
		if (pageSize==null||pageSize <= 0) pageSize = 5;
		
		Map<String, Object> queryMap = new HashMap<String, Object>();
		queryMap.put("merchantId", id+"");
		Pagination pageGoods = merchantGoodsService.findPagination(queryMap, currentPage, pageSize);
		
		jsonMap.put("status", Constants.Base.SUCCESS);
		jsonMap.put("msg", "成功");
		jsonMap.put("merchant", mer);
		jsonMap.put("imagesList", listMerImages);
		jsonMap.put("storeList", listMerStore);
		jsonMap.put("goodsList", pageGoods);
		return jsonMap;
    }
	
	
	@RequestMapping("/queryMerchantKeyword")
	@ResponseBody
	public Map<String, Object> queryMerchantKeyword(String keyword,Integer currentPage,Integer pageSize,
																				Model model,HttpServletRequest request,HttpServletResponse response){
		jsonMap.clear();
		Map<String, Object> params = super.getRequestParameters(request);
		if (currentPage==null || currentPage<=0) currentPage = Pagination.CURRENTPAGE;
		if (pageSize==null||pageSize <= 0) pageSize = 5;
		
		//先按类别查找
		CategoryExample criteria = new CategoryExample();
		criteria.createCriteria().andNameLike("%"+keyword+"%");
		List<Category> cateList = categoryService.findByCriteria(criteria);
		if(cateList !=null && cateList.size()>0){
			params.put("cateList", cateList);
		}
		
		params.put("is_publish", "1");
		Pagination page = merchantService.findPagination(params, currentPage, pageSize);
		jsonMap.put("status", Constants.Base.SUCCESS);
		jsonMap.put("msg", "成功");
		jsonMap.put("datas", page.getItems());
		jsonMap.put("currentPage", page.getCurrentPage());
		jsonMap.put("pageSize",page.getPageSize());
		jsonMap.put("totalCount", page.getTotalCount());
		return jsonMap;
	}
	
	
	@RequestMapping("/queryMerchantForLatestPublish")
	@ResponseBody
	public Map<String, Object> queryMerchantForLatestPublish(Integer currentPage,Integer pageSize,
																				Model model,HttpServletRequest request,HttpServletResponse response){
		jsonMap.clear();
		Map<String, Object> params = super.getRequestParameters(request);
		if (currentPage==null || currentPage<=0) currentPage = Pagination.CURRENTPAGE;
		if (pageSize==null||pageSize <= 0) pageSize = 5;
		
		params.put("latestpublish", "true");
		params.put("is_publish", "1");
		Pagination page = merchantService.findPagination(params, currentPage, pageSize);
		jsonMap.put("status", Constants.Base.SUCCESS);
		jsonMap.put("msg", "成功");
		jsonMap.put("datas", page.getItems());
		jsonMap.put("currentPage", page.getCurrentPage());
		jsonMap.put("pageSize",page.getPageSize());
		jsonMap.put("totalCount", page.getTotalCount());
		return jsonMap;
		
	}


	private Pagination computPagination(int currentPage, int pageSize,
			List<Merchant> listMerchant) {
		int totalCount = listMerchant.size();
		int pcount = totalCount%pageSize == 0 ? totalCount/pageSize : totalCount/pageSize + 1;
		if(currentPage>pcount){
			currentPage = 1;
		}
		List<Merchant> items = new ArrayList<Merchant>(pageSize);
		for (int i = (currentPage-1)*pageSize; i < (currentPage-1)*pageSize + pageSize; i++) {
			if(i>=totalCount){
				break;
			}
			items.add(listMerchant.get(i));
		}
		Pagination page = new Pagination(pageSize, currentPage, totalCount, items);
		return page;
	}


	private List<Merchant> filterByDistanceType(int distanceType,float userLo,float userLa,List<Merchant> listMerchant) {
		int disTarget =  distanceType==1?1*1000:(distanceType==2?3*1000:5*1000);
		Iterator<Merchant> ite = listMerchant.iterator();
		while(ite.hasNext()){
			Merchant mer = ite.next();
			if(userLo==0 && userLa==0){
				mer.setWithUserDistance(Integer.MAX_VALUE);
			}else{
				LocationUtil.Point p1 = new LocationUtil.Point(userLo,userLa);
				LocationUtil.Point p2 = new LocationUtil.Point(mer.getLongitude().floatValue(),mer.getLatitude().floatValue());
		        float twoDis = LocationUtil.distance(p1, p2);
		        if(twoDis>disTarget){
		        	ite.remove();
		        }else{
		        	mer.setWithUserDistance(twoDis);
		        }
			}
			
		}
		return null;
	}

}
